package cn.icybear.orzjisp.bytefile;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

public class CodeSection extends DefualtSection {
	public ArrayList<Section> subSections = new ArrayList<Section>();

	private LineNumberTable lineNumberTable;
	protected int code_len;

	public CodeSection() {
		super.tag = TAG_CODE;
	}

	public CodeSection(DataInputStream is) throws IOException {
		read = true;
		this.tag = is.readUnsignedByte();
		if (tag != TAG_CODE)
			throw new IOException("Unexcepted tag found:" + tag);
		@SuppressWarnings("unused")
		int len = is.readInt();
		code_len = is.readInt();
		readData(is, code_len);
		int sec_c = is.readUnsignedShort();
		// System.out.println("Sec_count="+sec_c);
		for (int i = 0; i < sec_c; i++) {
			subSections.add(DefualtSection.readSection(is));
		}
	}

	public int getCodeOffset() {
		return readBuffer.position();
	}

	public int getCodeLineNumber(int offset) {
		if (lineNumberTable == null) {
			for (Section s : subSections) {
				if (s instanceof LineNumberTable) {
					lineNumberTable = (LineNumberTable) s;
					break;
				}
			}
			if (lineNumberTable == null)
				return -1;
		}
		return lineNumberTable.findLine(offset);
	}

	@Override
	public synchronized int size() {
		int l = 6;// code_len(int)+count(short)
		for (Section s : subSections) {
			l += s.getLength();
		}
		return super.size() + l;
	}

	@Override
	protected void writeAddionalHeader(DataOutputStream os) throws IOException {
		os.writeInt(count);// Code length
	}

	@Override
	public void writeTo(OutputStream out) throws IOException {
		DataOutputStream writer = (out instanceof DataOutputStream) ? (DataOutputStream) out
				: new DataOutputStream(out);
		super.writeTo(writer);// Header,Code Len,Code
		writer.writeShort(subSections.size());
		for (Section s : subSections) {
			s.writeTo(writer);
		}
	}

	@Override
	public CodeSection clone() {
		// TODO Auto-generated method stub
		return (CodeSection) super.clone();
	}

}
